<?php

include "${__SITE_PATH}/mainthing/controller/main.php";

Class Router {
	private $registry;
	private $path;
	private $args = array();

	public $file;
	public $controller;
	public $action;

	function __construct($registry) {
		$this->registry = $registry;
	}

	function setPath($path) {
		if (!is_dir($path)) {
			throw new Exception("Invalid controller path: '$path'");
		}

		$this->path = $path;
	}

	public function loader() {
		$this->getController();

		if (!is_readable($this->file)) {
			$this->file = "{$this->path}/error404.php";
			$this->controller = "error404";
		}

		include $this->file;

		$class = ucwords($this->controller) . ucwords($this->action);
		$controller = new $class($this->registry);

		$main = new PhenotypicMain($this->registry);
		$main->execute($controller);
	}

	private function getController() {
		$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];

		if (empty($route)) $route = "index";
		else {
			$parts = explode("/", $route);
			$this->controller = $parts[0];
			if (isset($parts[1])) $this->action = $parts[1];
		}

		if (empty($this->controller)) $this->controller = "index";
		if (empty($this->action)) $this->action = "index";

		$this->file = "{$this->path}/{$this->controller}/controller/{$this->action}.php";
	}
}

?>